const { User, Resource } = require('../models');

/**
 * 保存资源到资源库
 * @route POST /api/resource/save
 */
const saveResource = async (req, res, next) => {
  try {
    const { resourceId, userId = 1 } = req.body;
    
    // 1. 检查资源是否存在
    const resource = await Resource.findByPk(resourceId);
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '资源不存在'
      });
    }
    
    // 2. 检查资源是否属于该用户
    if (resource.userId !== userId) {
      return res.status(403).json({
        code: 403,
        success: false,
        message: '无权操作该资源'
      });
    }
    
    // 3. 更新资源状态为已保存
    await resource.update({ isSaved: true });
    
    // 4. 返回结果
    res.json({
      code: 200,
      success: true,
      message: '资源已保存到资源库',
      data: {
        resourceId: resource.id,
        isSaved: true
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户资源列表
 * @route GET /api/resource/list
 */
const getResourceList = async (req, res, next) => {
  try {
    const { userId = 1, type, isSaved, page = 1, pageSize = 10 } = req.query;
    
    // 构建查询条件
    const whereCondition = { userId };
    if (type) {
      whereCondition.type = type;
    }
    if (isSaved !== undefined) {
      whereCondition.isSaved = isSaved === 'true';
    }
    
    // 分页查询
    const offset = (page - 1) * pageSize;
    const { count, rows } = await Resource.findAndCountAll({
      where: whereCondition,
      order: [['generateTime', 'DESC']],
      limit: parseInt(pageSize),
      offset: offset
    });
    
    // 格式化资源列表，根据不同类型提取关键信息
    const formattedResources = rows.map(resource => {
      const baseInfo = {
        id: resource.id,
        type: resource.type,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      };
      
      // 根据资源类型提取不同的关键信息
      switch (resource.type) {
        case 'design':
          return {
            ...baseInfo,
            title: resource.content.title || '未命名教学设计',
            objectives: resource.content.objectives || [],
            duration: resource.content.duration
          };
        case 'image':
          return {
            ...baseInfo,
            imageUrl: resource.content.imageUrl,
            prompt: resource.content.prompt,
            style: resource.content.style
          };
        case 'video':
          return {
            ...baseInfo,
            videoUrl: resource.content.videoUrl,
            duration: resource.content.duration,
            animationStyle: resource.content.animationStyle
          };
        case 'exercise':
          return {
            ...baseInfo,
            knowledgePoints: resource.content.knowledgePoints || [],
            totalCount: resource.content.totalCount || 0,
            questionTypes: resource.content.questionTypes || []
          };
        case 'paper':
          return {
            ...baseInfo,
            title: resource.content.title || '未命名试卷',
            totalScore: resource.content.totalScore || 100,
            examDuration: resource.content.examDuration || 120,
            coverage: resource.content.coverage
          };
        default:
          return baseInfo;
      }
    });
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        resources: formattedResources,
        pagination: {
          total: count,
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          totalPages: Math.ceil(count / pageSize)
        }
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取资源详情
 * @route GET /api/resource/:resourceId
 */
const getResourceDetail = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 查询资源
    const resource = await Resource.findByPk(resourceId);
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '资源不存在'
      });
    }
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        id: resource.id,
        userId: resource.userId,
        type: resource.type,
        content: resource.content,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除资源
 * @route DELETE /api/resource/:resourceId
 */
const deleteResource = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    const { userId = 1 } = req.query;
    
    // 1. 检查资源是否存在
    const resource = await Resource.findByPk(resourceId);
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '资源不存在'
      });
    }
    
    // 2. 检查资源是否属于该用户
    if (resource.userId !== parseInt(userId)) {
      return res.status(403).json({
        code: 403,
        success: false,
        message: '无权操作该资源'
      });
    }
    
    // 3. 删除资源
    await resource.destroy();
    
    // 4. 返回结果
    res.json({
      code: 200,
      success: true,
      message: '资源已删除',
      data: {
        resourceId
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  saveResource,
  getResourceList,
  getResourceDetail,
  deleteResource
};